Enumerations are commonly used to identify
distinct elements from a set of values.
However, they can also serve as bit flags, enabling bitwise operations to combine multiple
elements within a single value.
// Saturday = 0b00100000, Sunday = 0b01000000, weekend = 0b01100000
var weekend = Days.Saturday | Days.Sunday; // Combining elements
When enumerations are used as bit flags, it is considered good practice to
annotate the enum type with the FlagsAttribute:
enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4
}
// ...
var x = Permissions.Read | Permissions.Write; // Noncompliant: enum is not annotated with [Flags]
The FlagsAttribute
explicitly marks an enumeration as bit flags, making it clear that it uses bit fields and is intended to be used as
flags.
[Flags]
enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4
}
// ...
var x = Permissions.Read | Permissions.Write; // Compliant: enum is annotated with [Flags]
Additionally, adding the FlagsAttribute
to the enumeration enable a better string representation when using the Enum.ToString method.